package br.com.web.panificadora.controller;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import br.com.web.panificadora.beans.Login;
import br.com.web.panificadora.beans.Usuario;
import br.com.web.panificadora.services.LoginServices;
import br.com.web.panificadora.services.UsuarioServices;

@Controller
public class LoginController {
	
	@Autowired
	private LoginServices loginServices;
	
	@Autowired
	private UsuarioServices usuarioServices;
	
	/*DIRECIONA PARA O INDEX*/
	@RequestMapping(value = "/")
	public String login(){
		return "index";
	}
	

	@RequestMapping(value = "/logar")
	public ModelAndView logar(Login loginPage, HttpSession session){
		
		
		if (session.getAttribute("userSession") == null) {

			if ( !StringUtils.isBlank(loginPage.getUsuario())
					&& !StringUtils.isBlank(loginPage.getSenha()) ) {

				Login l = loginServices.getByUsuario(loginPage.getUsuario());

				if (l.getSenha().equals(loginPage.getSenha())) {

					Usuario usuario = usuarioServices.getByLogin(loginPage);
					session.setAttribute("userSession", usuario);

					return new ModelAndView("home");
				}

			}

		}else {
			return new ModelAndView("home");
		}
		
		return new ModelAndView("index");

	}
	
	@RequestMapping(value = "/logout")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:/";
	}
	

}
